package com.gitee.zhuyunlong2018.mybatisplusrelations.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gitee.zhuyunlong2018.mybatisplusrelations.Relations;
import com.gitee.zhuyunlong2018.mybatisplusrelations.binder.IBinder;
import com.gitee.zhuyunlong2018.mybatisplusrelations.context.IContext;
import com.gitee.zhuyunlong2018.mybatisplusrelations.func.IGetter;

import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Stream;


public class EntityBindOneHandler<T, R> extends EntityHandler<T, R> {


    private R foreignEntity;

    public EntityBindOneHandler(IContext<T> context, IGetter<T, ?> propertyGetter) {
        super(context, propertyGetter);
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    protected void queryRelation() {
        if (foreignEntity == null) {
            foreignEntityList = (List<R>) getForeignModel()
                    .selectList((LambdaQueryWrapper) getQueryWrapper());
            if (foreignEntityList == null || foreignEntityList.isEmpty()) {
                return;
            }
            foreignEntityList = covertListModelToVO(foreignEntityList);
            if (streamStatus) {
                Stream<R> stream = getForeignStream(foreignEntityList);
                // 有传入过滤器，进行过滤后取第一个
                foreignEntity = stream
                        .findFirst()
                        .orElse(null);
            } else {
                foreignEntity = foreignEntityList.get(0);
            }
        }
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    protected void buildRelation() {
        cache.getRelationEntitySetter().accept(entity, foreignEntity);
    }

    @Override
    protected IBinder<R> deepBinder() {
        return Relations.with(foreignEntity);
    }

    /**
     * 深度绑定
     *
     * @param binderConsumer
     * @return
     */
    public IBinder<T> deepWith(Consumer<IBinder<R>> binderConsumer) {
        deepBinderConsumer = binderConsumer;
        return binder;
    }

    @Override
    public IHandler<T, R> setForeignData(R foreignEntity) {
        this.foreignEntity = foreignEntity;
        return this;
    }
}
